import { Loading } from 'element-ui';
import { ADJUST_TYPES, KEY_STORES_TYPES, NON_KEY_STORES, HANDLE_TYPES } from '@/views/auto-config/constants';
import { message } from '@/utils/util';
import { save, getAutoConfig } from './api';

export default {
  metaInfo: {
    title: '自动化规则配置',
  },
  data() {
    return {
      adjustTypes: ADJUST_TYPES,
      keyStoresTypes: KEY_STORES_TYPES,
      nonKeyStoresTypes: NON_KEY_STORES,
      handleTypes: HANDLE_TYPES,
      labelWidth: '200px',
      autoConfig: {
        keyAutoConfigTrigger: {
          //重点门店触发
          id: '',
          adjustType: 'KEY_STORES',
          competePriceType: 'custom',
          competePriceChange: 'Y',
          competeChangePercent: '',
          salesChange: 'Y',
          salesChangePercent: null,
          salesChangeCycle: null,
          salesChangeType: 'custom',
          posChange: 'Y',
          posChangeType: 'custom',
          posChangePercent: null,
        },
        nonKeyAutoConfigTrigger: {
          //非重点门店触发
          id: '',
          adjustType: 'NON_KEY_STORES',
          competePriceType: 'custom',
          competePriceChange: 'Y',
          competeChangePercent: '',
          salesChange: 'Y',
          salesChangePercent: null,
          salesChangeCycle: null,
          salesChangeType: 'custom',
          posChange: 'Y',
          posChangeType: 'custom',
          posChangePercent: null,
        },
        keyAutoConfigCycleList: [
          //重点门店周期
          {
            id: '',
            adjustType: 'KEY_STORES',
            storePriority: '',
            handleType: '',
            handleDate: '',
            weeksDate: [],
            monthDate: [],
            dayDate: null,
          },
        ],
        nonKeyAutoConfigCycleList: [
          //非重点门店周期
          {
            id: '',
            adjustType: 'NON_KEY_STORES',
            storePriority: '',
            handleType: '',
            handleDate: '',
            weeksDate: [],
            monthDate: [],
            dayDate: null,
          },
        ],
        //满减活动周期
        fullAutoConfigCycle: {
          id: '',
          fullChange: 'Y',
          adjustType: 'FULL',
          storePriority: '',
          handleType: '',
          handleDate: '',
          weeksDate: [],
          monthDate: [],
          dayDate: null,
        },
        autoConfigAudit: {
          //需审核商品排名
          minSalesRank: null,
          maxSalesRank: null,
        },
      },
      month: [
        { id: '1', name: '01号' },
        { id: '2', name: '02号' },
        { id: '3', name: '03号' },
        { id: '4', name: '04号' },
        { id: '5', name: '05号' },
        { id: '6', name: '06号' },
        { id: '7', name: '07号' },
        { id: '8', name: '08号' },
        { id: '9', name: '09号' },
        { id: '10', name: '10号' },
        { id: '11', name: '11号' },
        { id: '12', name: '12号' },
        { id: '13', name: '13号' },
        { id: '14', name: '14号' },
        { id: '15', name: '15号' },
        { id: '16', name: '16号' },
        { id: '17', name: '17号' },
        { id: '18', name: '18号' },
        { id: '19', name: '19号' },
        { id: '20', name: '20号' },
        { id: '21', name: '21号' },
        { id: '22', name: '22号' },
        { id: '23', name: '23号' },
        { id: '24', name: '24号' },
        { id: '25', name: '25号' },
        { id: '26', name: '26号' },
        { id: '27', name: '27号' },
        { id: '28', name: '28号' },
        { id: '29', name: '29号' },
        { id: '30', name: '30号' },
        { id: '31', name: '31号' },
      ],
      weeks: [
        { id: '1', name: '周一' },
        { id: '2', name: '周二' },
        { id: '3', name: '周三' },
        { id: '4', name: '周四' },
        { id: '5', name: '周五' },
        { id: '6', name: '周六' },
        { id: '7', name: '周日' },
      ],
      onSubmitIng: false,
      formRules: {
        keyCycle: [
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!this.checkAutoConfigCycleList(this.autoConfig.keyAutoConfigCycleList)) {
                callback('请补全信息');
              } else {
                callback();
              }
            },
          },
        ],
        keyCompetePriceTrigger: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              const { competePriceChange, competePriceType, competeChangePercent } = this.autoConfig.keyAutoConfigTrigger;
              if (competePriceChange === 'Y' && competePriceType === 'custom' && !competeChangePercent) {
                callback('请补全信息');
              } else {
                callback();
              }
            },
          },
        ],
        keyPosPriceTrigger: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              const { posChange, posChangeType, posChangePercent } = this.autoConfig.keyAutoConfigTrigger;
              if (posChange === 'Y' && posChangeType === 'custom' && !posChangePercent) {
                callback('请补全信息');
              } else {
                callback();
              }
            },
          },
        ],
        keySalesTrigger: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              const { salesChange } = this.autoConfig.keyAutoConfigTrigger;
              if (!salesChange) {
                callback('请补全信息');
              } else {
                callback();
              }
            },
          },
        ],
        nonKeyCycle: [
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!this.checkAutoConfigCycleList(this.autoConfig.nonKeyAutoConfigCycleList)) {
                callback('请补全信息');
              } else {
                callback();
              }
            },
          },
        ],
        nonKeyCompetePriceTrigger: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              const { competePriceChange, competePriceType, competeChangePercent } = this.autoConfig.nonKeyAutoConfigTrigger;
              if (competePriceChange === 'Y' && competePriceType === 'custom' && !competeChangePercent) {
                callback('请补全信息');
              } else {
                callback();
              }
            },
          },
        ],
        nonKeyPosPriceTrigger: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              const { posChange, posChangeType, posChangePercent } = this.autoConfig.nonKeyAutoConfigTrigger;
              if (posChange === 'Y' && posChangeType === 'custom' && !posChangePercent) {
                callback('请补全信息');
              } else {
                callback();
              }
            },
          },
        ],
        nonKeySalesTrigger: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              const { salesChange } = this.autoConfig.nonKeyAutoConfigTrigger;
              if (!salesChange) {
                callback('请补全信息');
              } else {
                callback();
              }
            },
          },
        ],
        fullReduction: [
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              let { fullChange, handleType, weeksDate, monthDate, dayDate } = this.autoConfig.fullAutoConfigCycle;
              if (fullChange === 'Y') {
                if (!handleType) {
                  callback('请补全信息');
                }
                if (handleType === 'WEEKS' && weeksDate.length === 0) {
                  callback('请补全信息');
                }

                if (handleType === 'MONTH' && monthDate.length === 0) {
                  callback('请补全信息');
                }
                if (handleType === 'CYCLE' && !dayDate) {
                  callback('请补全信息');
                }
                callback();
              } else {
                callback();
              }
            },
          },
        ],
        salesRank: [
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              const { autoConfigAudit } = this.autoConfig;
              if (!autoConfigAudit.minSalesRank || !autoConfigAudit.maxSalesRank) {
                callback('请补全信息');
              } else if (autoConfigAudit.minSalesRank > autoConfigAudit.maxSalesRank) {
                callback('最小商品排名不能大于最大商品排名');
              } else {
                callback();
              }
            },
          },
        ],
      },
    };
  },
  methods: {
    addAutoConfigCycle(type) {
      if ('key' === type) {
        this.autoConfig.keyAutoConfigCycleList.push({
          id: '',
          adjustType: 'KEY_STORES',
          storePriority: '',
          handleType: 'CYCLE',
          handleDate: null,
          weeksDate: [],
          monthDate: [],
          dayDate: null,
        });
      }
      if ('nonKey' === type) {
        this.autoConfig.nonKeyAutoConfigCycleList.push({
          id: '',
          adjustType: 'NON_KEY_STORES',
          storePriority: '',
          handleType: 'CYCLE',
          handleDate: null,
          weeksDate: [],
          monthDate: [],
          dayDate: null,
        });
      }
    },
    checkAutoConfigCycleList(list) {
      let isTrue = true;
      if (list && list.length === 0) {
        isTrue = false;
        return isTrue;
      }
      list.forEach(item => {
        if (!isTrue) {
          return;
        }
        if (!item.adjustType) {
          isTrue = false;
        }
        if (!item.handleType) {
          isTrue = false;
        }
        if (item.handleType === 'WEEKS' && item.weeksDate.length === 0) {
          isTrue = false;
        }
        if (item.handleType === 'MONTH' && item.monthDate.length === 0) {
          isTrue = false;
        }
        if (item.handleType === 'CYCLE' && !item.dayDate) {
          isTrue = false;
        }
      });
      return isTrue;
    },
    removeAutoConfigCycle(index, type) {
      if ('key' === type) {
        if (this.autoConfig.keyAutoConfigCycleList.length === 1) {
          message('提示', '至少保留一个', 'warning');
          return;
        }
        this.autoConfig.keyAutoConfigCycleList.splice(index, 1);
      }
      if ('nonKey' === type) {
        if (this.autoConfig.nonKeyAutoConfigCycleList.length === 1) {
          message('提示', '至少保留一个', 'warning');
          return;
        }
        this.autoConfig.nonKeyAutoConfigCycleList.splice(index, 1);
      }
    },
    async reset() {
      await this.getAutoConfig();
    },
    onSubmit(name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          console.log('this.autoConfig:', this.autoConfig);
          let autoConfig = {
            autoConfigTriggerList: [],
            autoConfigCycleList: [],
            autoConfigAudit: {},
          };
          const {
            autoConfigAudit,
            keyAutoConfigCycleList,
            nonKeyAutoConfigCycleList,
            fullAutoConfigCycle,
            keyAutoConfigTrigger,
            nonKeyAutoConfigTrigger,
          } = this.autoConfig;
          if (autoConfigAudit.minSalesRank > 0 && autoConfigAudit.maxSalesRank > 0) {
            autoConfig = {
              ...autoConfig,
              autoConfigAudit: { minSalesRank: autoConfigAudit.minSalesRank, maxSalesRank: autoConfigAudit.maxSalesRank },
            };
          }
          keyAutoConfigCycleList.forEach(item => {
            let handleDate;
            if (item.handleType === 'WEEKS') {
              handleDate = item.weeksDate.length > 0 ? item.weeksDate.join(',') : null;
            }
            if (item.handleType === 'MONTH') {
              handleDate = item.monthDate.length > 0 ? item.monthDate.join(',') : null;
            }
            if (item.handleType === 'CYCLE') {
              handleDate = item.dayDate;
            }
            autoConfig.autoConfigCycleList.push({
              adjustType: item.adjustType,
              storePriority: item.storePriority,
              handleTye: item.handleType,
              handleDate: handleDate,
            });
          });
          nonKeyAutoConfigCycleList.forEach(item => {
            let handleDate;
            if (item.handleType === 'WEEKS') {
              handleDate = item.weeksDate.length > 0 ? item.weeksDate.join(',') : null;
            }
            if (item.handleType === 'MONTH') {
              handleDate = item.monthDate.length > 0 ? item.monthDate.join(',') : null;
            }
            if (item.handleType === 'CYCLE') {
              handleDate = item.dayDate;
            }
            autoConfig.autoConfigCycleList.push({
              adjustType: item.adjustType,
              storePriority: item.storePriority,
              handleTye: item.handleType,
              handleDate: handleDate,
            });
          });
          if (fullAutoConfigCycle.fullChange === 'Y') {
            let handleDate;
            if (fullAutoConfigCycle.handleType === 'WEEKS') {
              handleDate = fullAutoConfigCycle.weeksDate.length > 0 ? fullAutoConfigCycle.weeksDate.join(',') : null;
            }
            if (fullAutoConfigCycle.handleType === 'MONTH') {
              handleDate = fullAutoConfigCycle.monthDate.length > 0 ? fullAutoConfigCycle.monthDate.join(',') : null;
            }
            if (fullAutoConfigCycle.handleType === 'CYCLE') {
              handleDate = fullAutoConfigCycle.dayDate;
            }
            autoConfig.autoConfigCycleList.push({
              adjustType: fullAutoConfigCycle.adjustType,
              storePriority: null,
              handleTye: fullAutoConfigCycle.handleType,
              handleDate: handleDate,
            });
            autoConfig.autoConfigTriggerList.push({
              adjustType: fullAutoConfigCycle.adjustType,
              competePriceChange: 'N',
              salesChange: 'N',
              posChange: 'N',
              fullChange: 'Y',
            });
          } else {
            autoConfig.autoConfigTriggerList.push({
              adjustType: fullAutoConfigCycle.adjustType,
              competePriceChange: 'N',
              salesChange: 'N',
              posChange: 'N',
              fullChange: 'N',
            });
          }
          autoConfig.autoConfigTriggerList.push({
            adjustType: keyAutoConfigTrigger.adjustType,
            competePriceChange: keyAutoConfigTrigger.competePriceChange,
            competeChangePercent: this.getPercent(keyAutoConfigTrigger.competePriceChange, keyAutoConfigTrigger.competePriceType)
              ? keyAutoConfigTrigger.competeChangePercent
              : null,
            salesChange: keyAutoConfigTrigger.salesChange,
            salesChangeCycle: keyAutoConfigTrigger.salesChange === 'Y' ? keyAutoConfigTrigger.salesChangeCycle : null,
            salesChangePercent: this.getPercent(keyAutoConfigTrigger.salesChange, keyAutoConfigTrigger.salesChangeType)
              ? keyAutoConfigTrigger.salesChangePercent
              : null,
            posChange: keyAutoConfigTrigger.posChange,
            posChangePercent: this.getPercent(keyAutoConfigTrigger.posChange, keyAutoConfigTrigger.posChangeType)
              ? keyAutoConfigTrigger.posChangePercent
              : null,
            fullChange: 'N',
          });
          autoConfig.autoConfigTriggerList.push({
            adjustType: nonKeyAutoConfigTrigger.adjustType,
            competePriceChange: nonKeyAutoConfigTrigger.competePriceChange,
            competeChangePercent: this.getPercent(nonKeyAutoConfigTrigger.competePriceChange, nonKeyAutoConfigTrigger.competePriceType)
              ? nonKeyAutoConfigTrigger.competeChangePercent
              : null,
            salesChange: nonKeyAutoConfigTrigger.salesChange,
            salesChangeCycle: nonKeyAutoConfigTrigger.salesChange === 'Y' ? nonKeyAutoConfigTrigger.salesChangeCycle : null,
            salesChangePercent: this.getPercent(nonKeyAutoConfigTrigger.salesChange, nonKeyAutoConfigTrigger.salesChangeType)
              ? nonKeyAutoConfigTrigger.salesChangePercent
              : null,
            posChange: nonKeyAutoConfigTrigger.posChange,
            posChangePercent: this.getPercent(nonKeyAutoConfigTrigger.posChange, nonKeyAutoConfigTrigger.posChangeType)
              ? nonKeyAutoConfigTrigger.posChangePercent
              : null,
            fullChange: 'N',
          });
          this.save(autoConfig);
        }
      });
    },
    aaa(a) {
      console.log(a);
    },
    getPercent(change, changeType) {
      return !(change === 'N' || changeType === 'random');
    },
    async save(autoConfig) {
      try {
        this.onSubmitIng = true;
        await save(autoConfig);
        message('提示', '操作成功', 'success');
      } catch (e) {
        console.log(e);
        message('错误', '操作失败', 'error');
      }
      this.onSubmitIng = false;
    },
    async getAutoConfig() {
      let loadingInstance = Loading.service({});
      try {
        const { autoConfigAudit = {}, autoConfigCycleList = [], autoConfigTriggerList = [] } = (await getAutoConfig()) || {};
        if (autoConfigAudit) {
          this.autoConfig = { ...this.autoConfig, autoConfigAudit: autoConfigAudit };
        } else {
          this.autoConfig = { ...this.autoConfig, autoConfigAudit: { minSalesRank: null, maxSalesRank: null } };
        }
        if (autoConfigCycleList && autoConfigCycleList.length > 0) {
          let keyAutoConfigCycleList = [];
          let nonKeyAutoConfigCycleList = [];
          let fullAutoConfigCycle = {
            adjustType: 'FULL',
            fullChange: 'N',
            storePriority: '',
            weeksDate: [],
            monthDate: [],
            dayDate: null,
          };
          autoConfigCycleList.forEach(item => {
            const { adjustType, handleTye } = item;
            let monthDate;
            let weeksDate;
            let dayDate;
            if (handleTye === 'WEEKS') {
              weeksDate = item.handleDate.split(',');
            }
            if (handleTye === 'MONTH') {
              monthDate = item.handleDate.split(',');
            }
            if (handleTye === 'CYCLE') {
              dayDate = Number(item.handleDate);
            }
            if (adjustType === 'KEY_STORES') {
              keyAutoConfigCycleList.push({
                id: item.id,
                adjustType: item.adjustType,
                storePriority: item.storePriority,
                handleType: item.handleTye,
                handleDate: item.handleDate,
                weeksDate: weeksDate || [],
                monthDate: monthDate || [],
                dayDate: dayDate || null,
              });
            }
            if (adjustType === 'NON_KEY_STORES') {
              nonKeyAutoConfigCycleList.push({
                id: item.id,
                adjustType: item.adjustType,
                storePriority: item.storePriority,
                handleType: item.handleTye,
                handleDate: item.handleDate,
                weeksDate: weeksDate || [],
                monthDate: monthDate || [],
                dayDate: dayDate || null,
              });
            }
            if (adjustType === 'FULL') {
              fullAutoConfigCycle = {
                ...fullAutoConfigCycle,
                id: item.id,
                fullChange: 'Y',
                adjustType: 'FULL',
                handleType: item.handleTye,
                handleDate: item.handleDate,
                weeksDate: weeksDate || [],
                monthDate: monthDate || [],
                dayDate: dayDate || null,
              };
              this.autoConfig.fullAutoConfigCycle = fullAutoConfigCycle;
            }
          });
          this.autoConfig.keyAutoConfigCycleList = keyAutoConfigCycleList;
          this.autoConfig.nonKeyAutoConfigCycleList = nonKeyAutoConfigCycleList;
        } else {
          this.autoConfig.keyAutoConfigCycleList = [
            {
              id: '',
              adjustType: 'KEY_STORES',
              storePriority: '',
              handleType: '',
              handleDate: '',
              weeksDate: [],
              monthDate: [],
              dayDate: null,
            },
          ];
          this.autoConfig.nonKeyAutoConfigCycleList = [
            {
              id: '',
              adjustType: 'NON_KEY_STORES',
              storePriority: '',
              handleType: '',
              handleDate: '',
              weeksDate: [],
              monthDate: [],
              dayDate: null,
            },
          ];
          this.autoConfig.fullAutoConfigCycle = {
            id: '',
            fullChange: 'N',
            adjustType: 'FULL',
            storePriority: '',
            handleType: '',
            handleDate: '',
            weeksDate: [],
            monthDate: [],
            dayDate: null,
          };
        }
        if (autoConfigTriggerList && autoConfigTriggerList.length > 0) {
          let keyAutoConfigTrigger = {};
          let nonKeyAutoConfigTrigger = {};
          autoConfigTriggerList.forEach(item => {
            const { adjustType, fullChange } = item;
            if (adjustType === 'KEY_STORES') {
              keyAutoConfigTrigger = {
                ...keyAutoConfigTrigger,
                id: item.id,
                adjustType: 'KEY_STORES',
                competePriceType: this.getChangeType(item.competePriceChange, item.competeChangePercent),
                competePriceChange: item.competePriceChange,
                competeChangePercent: item.competeChangePercent,
                salesChange: item.salesChange,
                salesChangePercent: item.salesChangePercent || null,
                salesChangeCycle: item.salesChangeCycle || null,
                salesChangeType: this.getChangeType(item.salesChange, item.salesChangePercent),
                posChange: item.posChange,
                posChangeType: this.getChangeType(item.posChange, item.posChangePercent),
                posChangePercent: item.posChangePercent,
              };
            }
            if (adjustType === 'NON_KEY_STORES') {
              nonKeyAutoConfigTrigger = {
                ...nonKeyAutoConfigTrigger,
                id: item.id,
                adjustType: 'NON_KEY_STORES',
                competePriceType: this.getChangeType(item.competePriceChange, item.competeChangePercent),
                competePriceChange: item.competePriceChange,
                competeChangePercent: item.competeChangePercent,
                salesChange: item.salesChange,
                salesChangePercent: item.salesChangePercent || null,
                salesChangeCycle: item.salesChangeCycle || null,
                salesChangeType: this.getChangeType(item.salesChange, item.salesChangePercent),
                posChange: item.posChange,
                posChangeType: this.getChangeType(item.posChange, item.posChangePercent),
                posChangePercent: item.posChangePercent,
              };
            }
            if (adjustType === 'FULL' && fullChange === 'N') {
              this.autoConfig.fullAutoConfigCycle.fullChange = 'N';
            }
          });
          this.autoConfig.keyAutoConfigTrigger = keyAutoConfigTrigger;
          this.autoConfig.nonKeyAutoConfigTrigger = nonKeyAutoConfigTrigger;
        } else {
          this.autoConfig.keyAutoConfigTrigger = {
            adjustType: 'KEY_STORES',
          };
          this.autoConfig.nonKeyAutoConfigTrigger = {
            adjustType: 'NON_KEY_STORES',
          };
        }
        console.log('autoConfig', this.autoConfig);
        this.$refs.formRef.resetFields();
      } catch (e) {
        message('错误', '获取配置异常', 'error');
      }
      this.$nextTick(() => {
        // 以服务的方式调用的 Loading 需要异步关闭
        loadingInstance.close();
      });
    },
    getChangeType(change, percent) {
      if (change === 'Y' && percent) {
        return 'custom';
      } else {
        return 'random';
      }
    },
    isDisabled(index, id, list) {
      let isDisabled = false;
      for (let i = 0; i < list.length; i++) {
        if (index !== i) {
          const storePriority = list[i].storePriority;
          if (id === storePriority) {
            isDisabled = true;
          }
        }
      }
      return isDisabled;
    },
  },
  computed: {},
  async created() {},
  async mounted() {
    this.getAutoConfig();
  },
};
